package org.rescue.web.kml;

import java.sql.*;
import java.util.ArrayList;
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Generates a KML file containing polygons and points for locations 
 * specified in the GET.
 * 
 * @author jlickfet
 *
 */
public class KMLGenerator extends HttpServlet {
	
	String loginUser = "root";
    String loginPasswd = "mysql";
    String loginUrl = "jdbc:mysql://localhost:3306/kml";
	

	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

    	//ArrayList<Integer>testLocationIds = new ArrayList<Integer>();
    	//testLocationIds.add(1);
    	//testLocationIds.add(2);		
    	
    	
		PrintWriter out = response.getWriter();
		out.print(buildKML(strToIntList(request.getParameter("locationIds"))));
		
	}
	
	
	/**
	 * Convert a <code>String</code> of comma-separated integers
	 * to an <code>ArrayList</code> containing the integers as objects.
	 *
	 * @param csv a string of comma separated integer values
	 * @return a list of <code>Integer</code> objects.
	 */
	public static ArrayList strToIntList(String csv) {
		
		ArrayList<Integer> intList = new ArrayList<Integer>();

	    String[] s = csv.split(",");	    
	    for(int i=0; i<s.length; i++){
	    	Integer theInt = null;
	    	try {
	    		theInt = new Integer(s[i]);	    		
	    	}
	    	catch (NumberFormatException e ) {
	    		theInt = null;
	    	}
	    	if(theInt != null) {
	    		intList.add(theInt);
	    	}
	    }
	   	return intList;
	}
	
	

    public StringBuilder buildKML(ArrayList<Integer> locationIds) {

    	
    	String kmlStart = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://earth.google.com/kml/2.0\">\n";
    	String kmlFinish = "</kml>";
    	
    	StringBuilder kml = new StringBuilder(kmlStart);
    	
	    PreparedStatement stmt = null;
        ResultSet rs = null;
        Connection conn = null;
	    
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
	
			conn = DriverManager.getConnection(loginUrl,loginUser,loginPasswd);
			
			//TODO: add more ?!
			// for now takes only first 10 locations
	        stmt = conn.prepareStatement("select description,kml from kml where id in (?,?,?,?,?,?,?,?,?,?) ");
	        for (int i=0; i<10; i++){
	        	if(locationIds.size()>i){
	        		stmt.setInt(i+1, locationIds.get(i));	
	        	}
	        	else {
	        		stmt.setNull(i+1, java.sql.Types.INTEGER);
	        	}
	        }	        
	        rs = stmt.executeQuery();
	                 
	        while (rs.next()) {
	        	//String desc = rs.getString("description");
	        	//kml.append("\t" + desc + "\n");
	        	
	        	String kmlValue = rs.getString("kml");
	        	kml.append("\t" + kmlValue + "\n");
	        	
	        	/*InputStream is = rs.getAsciiStream("kml");
	        	InputStreamReader isr = new InputStreamReader(is);

	        	StringBuffer kmlValue = new StringBuffer();
	        	int nchars = 0;
	        	char[] buffer = new char[1024]; 
	        	while((nchars = isr.read(buffer)) != -1) {
	        		kmlValue.append(buffer,0,nchars);
	        	}
	        	is.close();*/
        	
	        	
	        }
	                
	        kml.append(kmlFinish);

	        rs.close();
	        stmt.close();
	        conn.close();
	        
	    }
	
		catch (SQLException ex) {
	        while (ex!=null){
	            System.err.println("SQLException: " + ex.getMessage());
	            System.err.println("SQLState: " + ex.getSQLState());
	            System.err.println("VendorError: " + ex.getErrorCode());
	            ex = ex.getNextException();
	        }
	    }
		catch (Exception ex) {
			System.err.println("Exception: " + ex.getMessage());
		}

		return kml;
    }

	
    public static void main(String[] args) {
           	
    	KMLGenerator g = new KMLGenerator();
    	
    	ArrayList<Integer>testLocationIds = new ArrayList<Integer>();
    	testLocationIds.add(1);
    	testLocationIds.add(2);
    	
    	String result = g.buildKML(testLocationIds).toString();
    	System.out.print(result);
    }	

}
